<script setup>
import {ref} from "vue";
import {getAllParentAuthList, getChildAuthList, editAuth, forbiddenAuth, unForbiddenAuth,
        addParentAuth, deleteParentAuth, addChildAuth, removeChildAuth} from "@/api/auth.js";
import {Delete, Edit, FolderAdd, Lock, Unlock} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";


const tableData = ref([])
const getAllParentAuths = async () => {
  let result = await getAllParentAuthList()
  console.log("getAllParentAuths")
  console.log(result.date)
  tableData.value = result.date

  if (tableData.value != null) {
    // 使用 Promise.all 等待所有异步操作完成
    const promises = tableData.value.map(async (item) => {
        //查询每一个父级权限的子级权限 并赋值给该父级权限对象的childAuths属性
      item.childAuths = await getRoleChildAuths(item.name)
    })
    await Promise.all(promises)
  }
}

const getRoleChildAuths = async (pidName) => {
  let result = await getChildAuthList(pidName)
  return result.date
}
getAllParentAuths()

//修改权限信息
const dialogTitle = ref('')
const editAuthData = ref({
  authId: null,
  name: '',
  uri: ''
})
const echoAuthData = ref({
  authId: null,
  name: '',
  uri: ''
})
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const editAuthButton = (row)=>{
  console.log("获取到的authId："+row.id)
  // editAuthData.value.authId = row.id
  editAuthData.value = {
    authId: row.id,
    name: row.name,
    uri: row.uri
  }
  dialogTitle.value = '修改权限信息'
  dialogFormVisible.value = true

  echoAuthData.value = {
    authId: row.authId,
    name: row.name,
    uri: row.uri
  }
}
  //确认提交修改
const submitEditAuth = async () => {
  let result = await editAuth(editAuthData.value.authId, editAuthData.value.name, editAuthData.value.uri)
  if (result.code === 200) {
    dialogFormVisible.value = false
    ElMessage.success("修改权限信息成功")
    //清空表单数据
    editAuthData.value = {
      authId: null,
      name: '',
      uri: ''
    }
    getAllParentAuths()
  }else {
    ElMessage.error("修改权限信息失败")
  }
}
  //取消修改
const cancelSubmitEditAuth = ()=>{
  dialogFormVisible.value = false
  //清空表单数据
  editAuthData.value = {
    authId: null,
    name: '',
    uri: ''
  }
}

//禁用权限
const forbiddenAuthButton = async (authId) => {
  let result = await forbiddenAuth(authId)
  if (result.code === 200) {
    ElMessage.success("禁用权限成功")
    getAllParentAuths()
  }else {
    ElMessage.error("禁用权限失败")
  }
}
//解禁权限
const unForbiddenAuthButton = async (authId) => {
  let result = await unForbiddenAuth(authId)
  if (result.code === 200) {
    ElMessage.success("解禁权限成功")
    getAllParentAuths()
  }else {
    ElMessage.error("解禁权限失败")
  }
}
const confirmForbiddenAuthButton = (authId) => {
  ElMessageBox.confirm(
      '确认要禁用该权限吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        forbiddenAuthButton(authId)
        ElMessage({
          type: 'success',
          message: '禁用成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '用户取消禁用',
        })
      })
}

//添加一级权限
const addParentAuthButton = ()=>{
  //清空表单数据
  editAuthData.value = {
    authId: null,
    name: '',
    uri: ''
  }
  dialogTitle.value = '添加一级权限'
  dialogFormVisible.value = true
}
const submitAddParentAuth = async () => {
  let result = await addParentAuth(editAuthData.value.name,editAuthData.value.uri)
  if (result.code === 200) {
    dialogFormVisible.value = false
    ElMessage.success("添加一级权限成功")
    //清空表单数据
    editAuthData.value = {
      authId: null,
      name: '',
      uri: ''
    }
    getAllParentAuths()
  }else {
    ElMessage.error("添加一级权限失败")
  }
}
//删除父级权限
const deleteValue = ref('')
const confirmDeleteParentAuthButton = async () => {
  let result = await deleteParentAuth(deleteValue.value)
  if (result.code === 200) {
    ElMessage.success("删除一级权限成功")
    getAllParentAuths()
  }else {
    ElMessage.error("删除一级权限失败")
  }
}

//添加子级权限
const addChildAuthData = ref({
  pidName: '',
  name: '',
  uri: ''
})
const addChildAuthButton = (pidName)=>{
  console.log("获取到的父级权限名称为："+pidName)
  addChildAuthData.value.pidName = pidName
  dialogFormVisible.value = true
  dialogTitle.value = '添加子权限'
}
const submitAddChildAuth = async () => {
  addChildAuthData.value.name = editAuthData.value.name
  addChildAuthData.value.uri = editAuthData.value.uri
  let result = await addChildAuth(addChildAuthData.value.pidName,addChildAuthData.value.name,addChildAuthData.value.uri)
  if (result.code === 200) {
    dialogFormVisible.value = false
    ElMessage.success("添加子权限成功")
    //清空表单数据
    addChildAuthData.value = {
      pidName: '',
      name: '',
      uri: ''
    }
    getAllParentAuths()
  }
}
//判断对话框点击确认时应该调用哪个方法提交
const handleSubmit = ()=>{
  if (dialogTitle.value === '添加一级权限') {
    submitAddParentAuth()
  }else if (dialogTitle.value === '添加子权限') {
    submitAddChildAuth()
  }else if (dialogTitle.value === '修改权限信息') {
    submitEditAuth()
  }else if (dialogTitle.value === '修改子权限信息') {
    editChildAuth()
  }
}

//删除子权限
const removeChildAuthButton = async (authName) => {
  let result = await removeChildAuth(authName)
  if (result.code === 200) {
    ElMessage.success("删除子权限成功")
    getAllParentAuths()
  }else {
    ElMessage.error("删除子权限失败")
  }
}
//修改子权限
const editChildAuthButton = (row)=>{
  console.log("获取到的row.name："+row.name)
  editAuthData.value = {
    authId: row.id,
    name: row.name,
    uri: row.uri
  }
  dialogTitle.value = '修改子权限信息'
  dialogFormVisible.value = true
}
const editChildAuth = async () => {
  let result = await editAuth(editAuthData.value.authId,editAuthData.value.name,editAuthData.value.uri)
  if (result.code === 200) {
    dialogFormVisible.value = false
    ElMessage.success("修改子权限信息成功")
    //清空表单数据
    editAuthData.value = {
      authId: null,
      name: '',
      uri: ''
    }
    getAllParentAuths()
  }else {
    ElMessage.error("修改子权限信息失败")
  }
 }

 //重复确认是否删除的框
const confirmIsDeleteButton = (authName,selectInfo) => {
  ElMessageBox.confirm(
      '确认要删除吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (selectInfo === '删除一级权限') {
          confirmDeleteParentAuthButton()
        }else if (selectInfo === '删除子权限') {
          removeChildAuthButton(authName)
        }
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除失败',
        })
      })
}
</script>

<template>
  <div class="authManagerContent">
    <h3>权限管理/查询/操作</h3>
    <el-table stripe :data="tableData" height="420">

      <el-table-column type="expand" >
        <!-- 插槽 二级表格 展示该父级权限的子权限列表 -->
        <template #default="props">
          <div m="5" style="margin-left: 100px">
            <h4>该一级权限的子权限</h4>
            <el-button type="primary" plain @click="addChildAuthButton(props.row.name)"><el-icon><FolderAdd/></el-icon>添加子权限</el-button>
            <el-table border :data="props.row.childAuths" >
              <el-table-column label="权限名称" prop="name" />
              <el-table-column label="权限uri" prop="uri" />
              <el-table-column label="父权限id" prop="pid" />
              <el-table-column label="操作" >
                <template #default="scope" >
                  <el-button type="primary" plain @click="editChildAuthButton(scope.row)"><el-icon><Edit/></el-icon>修改</el-button>
                  <el-button type="danger" plain @click="confirmIsDeleteButton(scope.row.name,'删除子权限')"><el-icon><Delete/></el-icon>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="权限名称" prop="name" width="180"/>
      <el-table-column label="权限uri" prop="uri" width="180" />
      <el-table-column label="是否禁用" prop="isDeleted" width="100" />
      <el-table-column label="子权限数量" prop="countSub" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" round @click="editAuthButton(scope.row)" :disabled="scope.row.name =='权限管理'">
            <el-icon><Edit/></el-icon>修改
          </el-button>
          <el-button type="success" round @click="unForbiddenAuthButton(scope.row.id)" :disabled="scope.row.name =='权限管理'" >
            <el-icon><Unlock/></el-icon>解禁
          </el-button>
          <el-button type="danger" round @click="confirmForbiddenAuthButton(scope.row.id)" :disabled="scope.row.name =='权限管理'" >
            <el-icon><Lock/></el-icon>禁用
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="addParentAuthButton()"><el-icon><FolderAdd/></el-icon>添加一级权限</el-button>

    <el-form class="demo-form-inline demo-form-inline1">
      <el-form-item label="权限名称">
        <el-select
            v-model="deleteValue"
            clearable
            placeholder="选择需要删除的权限"
            style="width: 240px"
        >
          <el-option
              v-for="item in tableData"
              :key="item.name"
              :label="item.name"
              :value="item.name"
              :disabled="item.name == '权限管理'"
          />
        </el-select>
        <el-button type="warning" @click="confirmIsDeleteButton('','删除一级权限')">删除</el-button>
      </el-form-item>
    </el-form>

  </div>

  <div>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
      <el-form :model="editAuthData">
        <el-form-item label="权限名称" :label-width="formLabelWidth">
          <el-input v-model="editAuthData.name" autocomplete="off" :placeholder="echoAuthData.name" />
        </el-form-item>
        <el-form-item label="权限uri" :label-width="formLabelWidth">
          <el-input v-model="editAuthData.uri" autocomplete="off" :placeholder="echoAuthData.uri" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelSubmitEditAuth()">取消</el-button>
          <el-button type="primary" @click="handleSubmit()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

<!--  <div>
    <el-dialog v-model="dialogFormVisibleAdd" title="添加一级权限" width="500">
      <el-form :model="editAuthData">
        <el-form-item label="权限名称" :label-width="formLabelWidth">
          <el-input v-model="editAuthData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="权限uri" :label-width="formLabelWidth">
          <el-input v-model="editAuthData.uri" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisibleAdd = false">取消</el-button>
          <el-button type="primary" @click="submitAddParentAuth">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>-->
</template>

<style scoped>
.authManagerContent {
  padding-left: 20px;
  margin-top: 10px;
}
</style>